<?php

abstract class Base_Auth
{
    const GUEST_Name = 'GUESTS';
    const GUEST_ROLE = 'guests';
    
    private static $authAdapter = null;
    private static $authStorage = null;
    
    private static $userIdentity= null;

    public static function authenticate($username, $password)
    {
        self::$authAdapter = new Zend_Auth_Adapter_DbTable(NULL,
                'users',
                'name',
                'pass',
                'MD5(?)'
            );
        self::$authAdapter
                ->setIdentity($username)
                ->setCredential($password);

        $authResult = self::$authAdapter->authenticate();
        if ($authResult->isValid()) {
            self::$authStorage = new Zend_Auth_Storage_Session();
            self::$authStorage->write(self::$authAdapter
                ->getResultRowObject(array('uid','name','mail','role','state','login')));
            self::setIdentity();
            
            return TRUE;
        }
    }
    
    private static function setIdentity()
    {
        if (self::$authStorage === null) {
            self::$authStorage = new Zend_Auth_Storage_Session();
        }
        if (!self::$authStorage->isEmpty()) {
            self::$userIdentity = self::$authStorage->read();
        }
    }
    
    public static function getIdentity()
    {
        if (self::$userIdentity === null) {
            self::setIdentity();
        }
        return self::$userIdentity;
    }
    
    public static function getUid()
    {
        $identity = self::getIdentity();
        return isset($identity->uid)? $identity->uid: 0;
    }
    
    public static function getName()
    {
        $identity = self::getIdentity();
        return isset($identity->name)? $identity->name: self::GUEST_NAME;
    }
    
    public static function getRole()
    {
        $identity = self::getIdentity();
        return isset($identity->role)? $identity->role: self::GUEST_ROLE;
    }
    
    public static function isLogin()
    {
        if (isset(self::getIdentity()->uid)) {
            return TRUE;
        }
    }

    public static function clearIdentity()
    {
        self::$userIdentity = null;
        
        return self::$authStorage->clear();
    }
}